package com.yidu.controller;

import com.yidu.dao.FlUserDao;
import com.yidu.entity.FlUser;
import com.yidu.service.FlUserService;
import com.yidu.utils.BaseMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * (FlUser)表控制层
 *
 * @author liandyao
 * @since 2021-07-29 16:19:52
 */
@RestController
@RequestMapping("flUser")
public class FlUserController {
    /**
     * 服务对象
     */
    @Resource
    private FlUserService flUserService;

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("/selectOne")
    public FlUser selectOne(Integer id) {
        return this.flUserService.queryById(id);
    }

    /**
     * 登录方法
     * @param user 用户
     * @return 响应信息
     */
    @PostMapping("/findLogin")
    public BaseMessage findLogin(FlUser user){
        FlUser po = flUserService.findLogin(user);
        if(po==null){
            return BaseMessage.NO("登录失败");
        }else{
            return BaseMessage.YES("登录成功",po);
        }
    }

    /**
     * 检查用户名是否存在
     * @param usName
     * @return
     */
    @PostMapping("/checkName")
    public BaseMessage checkName(String usName){
        FlUser po = flUserService.findByName(usName);
        if(po==null){
            return BaseMessage.YES("可以注册");
        }else{
            return BaseMessage.NO("已存在");
        }
    }

    /**
     * 注册
     * @param user
     * @return
     */
    @Transactional
    @PostMapping("/add")
    public BaseMessage insert(FlUser user){
        FlUser po =  flUserService.insert(user);
        if(po==null){
            return BaseMessage.NO("注册失败");
        }else{
            return BaseMessage.YES("注册成功",po);
        }
    }

    //使用java.util.Date 时,页面传过来报400错误,需要使用一下代码解决
    @InitBinder //绑定日期类型
    public void initBinder(ServletRequestDataBinder binder){
        binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"),
                true));
    }

}